<?php

namespace App\Libs;

class ResponseMessage {
    /**
     * 定义通用报错列表
     *
     * @return	array
     */
    private $failedCodeList;

    private $status;
    private $failedCode;
    private $failedMsg;
    private $data;
    static private $instance;

    public function __construct(){
        self::intFailedCodeList();
        $this->status = 'SUCCESS';
    }

    private function intFailedCodeList(){
        $this->failedCodeList = [
            'ERROR'                         => '未知错误',
            'NO_LOGIN'                      => '没有登录',
            'EAT_EVERY_DAY_ONLY_ONE'        => '好可怜，每天只能抽一次',
            'EAT_EVERY_DAY_NOT_START'       => "活动".\Config::get('app.eat_every_day_start_hour')."点才开始哦",
            'NOT_MEMBER'                    => '您还不是会员，赶快找店员更改身份吧',
            'PARAM_ERROR'                   => '参数错误',
            'LOW_STOCKS'                    => '库存不足',
            'RESOURCES_NOT_EXIST'           => '资源不存在',
            'ORDER_NOT_EXIST'               => '订单不存在',
            'VERIFICATION_CODE_ERROR'       => '验证码错误',
        ];
    }

    static public function getInstance(){
        if(!(self::$instance instanceof ResponseMessage)){
            self::$instance = new self;
        }
        return self::$instance;
    }

    public function success($data = []){
        $this->status = 'SUCCESS';
        $this->data = $data;
        return $this;
    }

    public function failed($failedCode = null){
        $this->status = 'FAILED';
        $this->failedCode = isset($this->failedCodeList[$failedCode])?$failedCode:'ERROR';
        $this->failedMsg = isset($this->failedCodeList[$failedCode])?$this->failedCodeList[$failedCode]:'未知错误';
        return $this;
    }

    public function setStatus($status){
        $this->status = $status;
        return $this;
    }

    public function setFailedCode($failedCode, $failedMsg){
        $this->failedCode = $failedCode;
        $this->failedMsg = $failedMsg;
        return $this;
    }

    public function setData($data){
        $this->data = $data;
        return $this;
    }

    public function response(){
        if($this->status == 'SUCCESS'){
            $response = ['status' => $this->status, 'data' => $this->data];
        }else{
            $response = ['status' => $this->status, 'failedCode' => $this->failedCode, 'failedMsg' => $this->failedMsg];
        }
//        BLogger::getLogger(BLogger::LOG_RESPONSE)->info(json_encode($response));
        return $response;
    }
}
